<?php


namespace App\Service;


use App\Job\SendJob;
use App\Model\Device;
use App\Utils\Logger;
use Carbon\Carbon;
use App\Model\Normal;
use GuzzleHttp\Client;
use Hyperf\AsyncQueue\Driver\DriverFactory;
use Hyperf\Guzzle\CoroutineHandler;
use Hyperf\Guzzle\HandlerStackFactory;
use Hyperf\Utils\ApplicationContext;

class CallbackMqttService
{
    protected $driver;
    public function __construct(DriverFactory $driverFactory)
    {
        $this->driver = $driverFactory->get('default');
    }


    public function publish($data)
    {
        if($data['api_url']){
            return $this->driver->push(new SendJob($data));
        }
    }

    public static function curlPost($url, $data, $type = 'json', $charset = 'UTF-8')
    {
        $container = ApplicationContext::getContainer();
        $handlerStackFactory = $container->get(HandlerStackFactory::class);
        $handlerStack = $handlerStackFactory->create();
        $client = new Client(['handler' => new CoroutineHandler($handlerStack)]);

        // 根据传输类型设置不同的 Content-Type
        $contentType = $type === 'json' ? 'application/json' : 'application/x-www-form-urlencoded';

        $requestOptions = [
            'headers' => [
                'Content-Type' => $contentType . ';charset=' . $charset,
            ]
        ];

        // 根据类型添加数据
        if ($type === 'json') {
            $requestOptions['json'] = $data;
        } else {
            $requestOptions[$type] = $data;
        }

        $response = $client->post($url, $requestOptions);
        return $response->getBody()->getContents();
    }


}
